package cn.ac.jaas.isc.vegetable.pbms.service.impl;

import cn.ac.jaas.isc.vegetable.common.core.util.R;
import cn.ac.jaas.isc.vegetable.common.security.service.VegetableUser;
import cn.ac.jaas.isc.vegetable.common.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ac.jaas.isc.vegetable.pbms.api.entity.ArcDevice;
import cn.ac.jaas.isc.vegetable.pbms.mapper.ArcDeviceMapper;
import cn.ac.jaas.isc.vegetable.pbms.service.ArcDeviceService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 装置表
 *
 * @author 张高昌
 * @date 2022-05-22 19:51:08
 */
@Service
@AllArgsConstructor
public class ArcDeviceServiceImpl extends ServiceImpl<ArcDeviceMapper, ArcDevice> implements ArcDeviceService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveDevice(ArcDevice arcDevice, HttpServletRequest request) {
        LambdaQueryWrapper<ArcDevice> ecWrapper = Wrappers.lambdaQuery();
        ecWrapper.eq(ArcDevice::getDeviceCode, arcDevice.getDeviceCode());
        ArcDevice dModel = baseMapper.selectOne(ecWrapper);
        if (dModel != null) {
            return R.failed("装置编码已存在！");
        }

        VegetableUser user = SecurityUtils.getUser();
        arcDevice.setCreateTime(LocalDateTime.now());
        arcDevice.setCreateUser(user.getId());
        baseMapper.insertDevice(arcDevice);
        this.addDeviceHistory(arcDevice, request);
        return R.ok(true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R updateDevice(ArcDevice arcDevice, HttpServletRequest request) {
        LambdaQueryWrapper<ArcDevice> ecWrapper = Wrappers.lambdaQuery();
        ecWrapper.eq(ArcDevice::getDeviceCode, arcDevice.getDeviceCode())
                .ne(ArcDevice::getDeviceId, arcDevice.getDeviceId());
        ArcDevice dModel = baseMapper.selectOne(ecWrapper);
        if (dModel != null) {
            return R.failed("装置编码已存在！");
        }
        VegetableUser user = SecurityUtils.getUser();
        arcDevice.setUpdateTime(LocalDateTime.now());
        arcDevice.setUpdateUser(user.getId());
        baseMapper.updateByPrimaryKey(arcDevice);
        this.addDeviceHistory(arcDevice, request);
        return R.ok(true);
    }

    /**
     * 添加装置历史记录
     *
     * @param arcDevice
     * @param request
     */
    private void addDeviceHistory(ArcDevice arcDevice, HttpServletRequest request) {
    }
}
